﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Text;
using System.Windows;
using System.Windows.Data;
using Microsoft.Practices.Prism.Commands;
using ParaEditor.Common;
using ParaEditor.DAO;
using ParaEditor.DAO.ParaDAO;
using ParaEditor.Desktop.Helper;
using ParaEditor.Desktop.Interfaces;
using ParaEditor.Domain.Entities;
using ParaEditor.DomainSource.Entities;
using ParaEditor.Infrastructure;

namespace ParaEditor.Desktop.ViewModel
{
    [Export(typeof(IPara4004ViewModel))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class Para4004ViewModel : ViewModelBase, IPara4004ViewModel
    {
        private Para4004DAO paramDao;
        private SourceBaseDAO sDao;

        private ICollectionView infoVerList;
        public ICollectionView InfoVerList
        {
            get
            {
                return infoVerList;
            }
            set
            {
                this.infoVerList = value;
                this.RaisePropertyChangedEvent("InfoVerList");
            }
        }

        private ICollectionView paraCollectionDetail;
        public ICollectionView ParaCollectionDetail
        {
            get
            {
                return this.paraCollectionDetail;
            }
            set
            {
                this.paraCollectionDetail = value;
                this.RaisePropertyChangedEvent("ParaCollectionDetail");
            }
        }

        private Visibility editGroupBoxVisible;
        public Visibility EditGroupBoxVisible
        {
            get
            {
                return this.editGroupBoxVisible;
            }
            set
            {
                this.editGroupBoxVisible = value;
                this.RaisePropertyChangedEvent("EditGroupBoxVisible");
            }
        }

        private ICollectionView baseScLineList;
        public ICollectionView BaseScLineList
        {
            get
            {
                return baseScLineList;
            }
            set
            {
                this.baseScLineList = value;
                this.RaisePropertyChangedEvent("BaseScLineList");
            }
        }

        private ICollectionView baseScList;
        public ICollectionView BaseScList
        {
            get
            {
                return baseScList;
            }
            set
            {
                this.baseScList = value;
                this.RaisePropertyChangedEvent("BaseScList");
            }
        }

        private ICollectionView lineList;
        public ICollectionView LineList
        {
            get
            {
                return lineList;
            }
            set
            {
                this.lineList = value;
                this.RaisePropertyChangedEvent("LineList");
            }
        }

        private ICollectionView stationList;
        public ICollectionView StationList
        {
            get
            {
                return stationList;
            }
            set
            {
                this.stationList = value;
                this.RaisePropertyChangedEvent("StationList");
            }
        }

        private int areaID;
        public int AreaID
        {
            get
            {
                return this.areaID;
            }
            set
            {
                this.areaID = value;
                this.RaisePropertyChangedEvent("AreaID");
            }
        }

        private short areaInfo;
        public short AreaInfo
        {
            get
            {
                return this.areaInfo;
            }
            set
            {
                this.areaInfo = value;
                this.RaisePropertyChangedEvent("AreaInfo");
            }
        }

        private int progress1;
        public int Progress1
        {
            get
            {
                return this.progress1;
            }
            set
            {
                this.progress1 = value;
                this.RaisePropertyChangedEvent("Progress1");
            }
        }

        private Visibility progressVisibility;
        public Visibility ProgressVisibility
        {
            get
            {
                return this.progressVisibility;
            }
            set
            {
                this.progressVisibility = value;
                this.RaisePropertyChangedEvent("ProgressVisibility");
            }
        }

        private string timeSpan;
        public string TimeSpan
        {
            get
            {
                return this.timeSpan;
            }
            set
            {
                this.timeSpan = value;
                this.RaisePropertyChangedEvent("TimeSpan");
            }
        }

        //Button
        public DelegateCommand AddParamCommand { get; private set; }
        public DelegateCommand DelParamCommand { get; private set; }
        public DelegateCommand SaveParamCommand { get; private set; }
        public DelegateCommand CanclEditParamCommand { get; private set; }
        public DelegateCommand NewVersionCommand { get; private set; }
        public DelegateCommand CopyCurrentVersionCommand { get; private set; }
        public DelegateCommand ImportDateCommand { get; private set; }

        private BackgroundWorker worker;
        private BackgroundWorker workerReportProgress;

        [ImportingConstructor]
        public Para4004ViewModel()
        {
            sDao = new SourceBaseDAO();
            paramDao = new Para4004DAO();
            InfoVerList = CollectionViewSource.GetDefaultView(paramDao.GetAllVersion());
            if (paramDao.GetAllVersion().Count == 0)
            {
                Microsoft.Windows.Controls.MessageBox.Show("当前参数无任何参数版本");
            }
            InfoVerList.CurrentChanged += InfoVerList_CurrentChanged;

            EditGroupBoxVisible = Visibility.Hidden;

            BaseScLineList = CollectionViewSource.GetDefaultView(paramDao.GetCurrentLine());
            BaseScLineList.CurrentChanged += BaseScLineList_CurrentChanged;

            LineList = CollectionViewSource.GetDefaultView(paramDao.GetCurrentLine());
            LineList.CurrentChanged += LineList_CurrentChanged;


            this.worker = new BackgroundWorker();
            this.worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            this.worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            this.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            this.worker.WorkerReportsProgress = true;
            

            //Button
            this.AddParamCommand = new DelegateCommand(this.AddParam);
            this.DelParamCommand = new DelegateCommand(this.DelParam);
            this.SaveParamCommand = new DelegateCommand(this.SaveParam);
            this.CanclEditParamCommand = new DelegateCommand(this.CanclEditParam);
            this.NewVersionCommand = new DelegateCommand(this.NewVersion);
            this.CopyCurrentVersionCommand = new DelegateCommand(this.CopyCurrentVersion);
            this.ImportDateCommand = new DelegateCommand(this.ImportDate);
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {

            if (InfoVerList.CurrentItem != null)
            {
                TimeSpan toNow;
                workerReportProgress = sender as BackgroundWorker;
                StringBuilder sb = new StringBuilder();
                IList<CalcArea> srcList = sDao.GetCurrentCalcArea();
                int infoVer = (int)InfoVerList.CurrentItem;
                int maxInfoVer = paramDao.GetMaxID();
                if (infoVer <= maxInfoVer)
                {
                    paramDao.Del4004ByInfoVerAndRecordID(infoVer);
                }

                IList<Para4004> dList = DomainConvert.ConvertToPara4004(srcList, infoVer);
                int count = dList.Count;
                int mod = count / 100;
                int yu = count - mod * 100;
                int i = 1;
                long startTimeSpan = DateTime.Now.Ticks;
                long currentTimeSpan = 0;
                for (int j = 0; j < 101; )
                {
                    for (; i <= count; i++)
                    {
                        paramDao.CreateObjectNonFlushSession(dList[i - 1]);
                        if (i % 1277 == 0)
                        {
                            paramDao.FlushSession();
                            currentTimeSpan = DateTime.Now.Ticks;
                            toNow = new TimeSpan((currentTimeSpan - startTimeSpan) / i);
                            sb.Clear();
                        }
                        sb.Append(i);
                        sb.Append(" of ");
                        sb.Append(count);
                        TimeSpan = sb.ToString();
                        sb.Clear();
                        if (i >= mod * j + yu)
                        {
                            j++;
                            paramDao.FlushSession();
                            workerReportProgress.ReportProgress(j);
                        }
                    }
                }
                paramDao.FlushSession();
                TimeSpan = "导入成功!";
            }
            else
            {
                TimeSpan = "请选择参数版本!";
            }
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.Progress1 = e.ProgressPercentage;
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.ProgressVisibility = Visibility.Hidden;
            FlashParaCollectionDetail();
        }

        private void ImportDate()
        {
            if (Microsoft.Windows.Controls.MessageBox.Show("确定导入数据？", "4004参数", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Question) == System.Windows.MessageBoxResult.OK)
            {
                this.ProgressVisibility = Visibility.Visible;
                worker.RunWorkerAsync();
            }
        }

        private void FlashParaCollectionDetail()
        {
            
            int infoVer = (int)InfoVerList.CurrentItem;
            string lineID = (BaseScList.CurrentItem as CurrentStation).LineID;
            string OwnerStationID = (BaseScList.CurrentItem as CurrentStation).StationID;
            ParaCollectionDetail = CollectionViewSource.GetDefaultView(paramDao.GetObjectByInfoVer(infoVer, lineID, OwnerStationID));
        }

        private void AddParam()
        {
            if (InfoVerList.CurrentItem == null)
            {
                Microsoft.Windows.Controls.MessageBox.Show("请添加参数版本！才可进行添加");
            }
            else
            {
                EditGroupBoxVisible = Visibility.Visible;
            }
        }

        private void CopyCurrentVersion()
        {
            //查询当前版本
            ObservableCollection<Para4004> currentVersionParam = new ObservableCollection<Para4004>();
            int infoVer = (int)InfoVerList.CurrentItem;
            string lineID = (BaseScList.CurrentItem as CurrentStation).LineID;
            string OwnerStationID = (BaseScList.CurrentItem as CurrentStation).StationID;
            currentVersionParam = paramDao.GetObjectByInfoVer(infoVer);

            if (currentVersionParam.Count != 0)
            {
                Para4004 param = null;
                Para4004Pk paramPk = null;
                int newVersion = paramDao.GetMaxID() + 1;
                foreach (Para4004 item in currentVersionParam)
                {
                    param = new Para4004(item);
                    paramPk = new Para4004Pk();
                    //编辑参数
                    paramPk.infoVer = Int16.Parse(newVersion.ToString());
                    paramPk.areaId = item.para4004Pk.areaId;
                    param.areaInfo = item.areaInfo;
                    param.para4004Pk = paramPk;

                    ResultValue result = paramDao.CreateObject(param);
                    if (result.Code != 0)
                    {
                        Microsoft.Windows.Controls.MessageBox.Show("复制过程中出现错误!错误信息：" + result.Msg);
                    }
                }
                //刷新
                ParaCollectionDetail = CollectionViewSource.GetDefaultView(paramDao.GetObjectByInfoVer(newVersion, lineID, OwnerStationID));
                InfoVerList = CollectionViewSource.GetDefaultView(paramDao.GetAllVersion());
                InfoVerList.CurrentChanged += InfoVerList_CurrentChanged;
            }
            else
            {
                Microsoft.Windows.Controls.MessageBox.Show("所查询的当前版本没有数据,不可进行复制");
            }
        }

        private void NewVersion()
        {
            ObservableCollection<int> infoVerCollection = new ObservableCollection<int>();
            infoVerCollection = paramDao.GetAllVersion();
            int newVersion = paramDao.GetMaxID() + 1;
            infoVerCollection.Add(newVersion);
            InfoVerList = CollectionViewSource.GetDefaultView(infoVerCollection);
            InfoVerList.CurrentChanged += InfoVerList_CurrentChanged;
        }

        private void DelParam()
        {
            try
            {
                if (ParaCollectionDetail.CurrentItem != null)
                {
                    Para4004 param = ParaCollectionDetail.CurrentItem as Para4004;
                    if (Microsoft.Windows.Controls.MessageBox.Show("确认删除所选择的参数！", "4004参数", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Question) == System.Windows.MessageBoxResult.OK)
                    {
                        //删除
                        ResultValue result = paramDao.DeleteObject(param, param.para4004Pk.infoVer);
                        if (result.Code == 0)
                        {
                            Microsoft.Windows.Controls.MessageBox.Show("删除成功");
                            //刷新
                            InfoVerList = CollectionViewSource.GetDefaultView(paramDao.GetAllVersion());
                            InfoVerList.CurrentChanged += InfoVerList_CurrentChanged;

                            ReflashDataGrid();

                        }
                        else
                        {
                            Microsoft.Windows.Controls.MessageBox.Show("删除失败!发生错误：" + result.Msg);
                        }
                    }
                }
                else
                {
                    Microsoft.Windows.Controls.MessageBox.Show("未选择要删除的参数");
                }
            }
            catch (Exception e)
            {
            }
        }

        public void SaveParam()
        {
            if (Confirm())
            {
                Para4004 param = new Para4004();
                Para4004Pk paramPk = new Para4004Pk();
                int tmp = (int)InfoVerList.CurrentItem;
                paramPk.infoVer = (int)InfoVerList.CurrentItem;
                paramPk.areaId = this.AreaID;

                param.para4004Pk = paramPk;
                param.inStationId = (this.StationList.CurrentItem as CurrentStation).StationID;
                param.ownerStation = (this.BaseScList.CurrentItem as CurrentStation).StationID;
                param.lineId = (BaseScList.CurrentItem as CurrentStation).LineID;
                param.areaResv = 0;
                param.areaInfo = this.AreaInfo;
                
                //编辑参数
                ResultValue result = paramDao.CreateObject(param);
                if (result.Code == 0)
                {
                    Microsoft.Windows.Controls.MessageBox.Show("保存成功");
                    ReflashDataGrid();

                    CanclEditParam();
                }
                else
                {
                    Microsoft.Windows.Controls.MessageBox.Show("保存失败！发生错误:" + result.Msg);
                }
            }
        }

        private void CanclEditParam()
        {
            this.EditGroupBoxVisible = Visibility.Hidden;
            //将控件置为空
            this.AreaID = 0;
        }

        private bool Confirm()
        {
            bool flag = true;
            /*
            if (this.LineID != null && !"".Equals(this.LineID) && this.LineNmCn != null && !"".Equals(this.LineNmCn) && !"".Equals(this.LineNmEn) && this.LineNmEn != null)
            {
                flag = true;
            }
            else
            {
                Microsoft.Windows.Controls.MessageBox.Show("所填信息不完整");
                flag = false;
            }
             */
            return flag;
        }

        void InfoVerList_CurrentChanged(object sender, System.EventArgs ep)
        {
            if (InfoVerList.CurrentItem != null)
            {
                ReflashDataGrid();
            }
        }

        private void ReflashDataGrid()
        {
            int infoVer = (int)InfoVerList.CurrentItem;
            if (BaseScList != null && InfoVerList != null)
            {
                if (BaseScList.CurrentItem != null && InfoVerList.CurrentItem != null)
                {
                    this.FlashParaCollectionDetail();
                }
            }
        }

        void BaseScLineList_CurrentChanged(object sender, System.EventArgs ep)
        {
            if (BaseScLineList.CurrentItem != null)
            {
                CurrentLine currentLineSelected = BaseScLineList.CurrentItem as CurrentLine;
                BaseScList = CollectionViewSource.GetDefaultView(paramDao.GetCurrentStation(currentLineSelected.LineID.Trim()));
                BaseScList.CurrentChanged += BaseScList_CurrentChanged;
                if (BaseScList.CurrentItem != null && InfoVerList.CurrentItem != null)
                {
                    this.FlashParaCollectionDetail();
                }
            }
        }

        void LineList_CurrentChanged(object sender, System.EventArgs ep)
        {
            if (LineList.CurrentItem != null)
            {
                CurrentLine currentLineSelected = LineList.CurrentItem as CurrentLine;
                StationList = CollectionViewSource.GetDefaultView(paramDao.GetCurrentStation(currentLineSelected.LineID.Trim()));
            }

            if (InfoVerList.CurrentItem != null && LineList.CurrentItem != null)
            {
                this.FlashParaCollectionDetail();
            }
        }

        void BaseScList_CurrentChanged(object sender, System.EventArgs ep)
        {
            if (BaseScList.CurrentItem != null && InfoVerList.CurrentItem != null)
            {
                this.FlashParaCollectionDetail();
            }
        }
    }
}
